import 'package:auto_route/auto_route.dart';
import 'package:casdon/app/config/theme/theme_extention.dart';
import 'package:casdon/build_gen/assets.gen.dart';
import 'package:casdon/common/widget/constom_tag_selector.dart';
import 'package:casdon/core/logger/log.dart';
import 'package:casdon/modules/recipe/application/notification/recipe_search_history_notifier.dart';
import 'package:casdon/modules/recipe/application/notification/recipe_search_notifier.dart';
import 'package:casdon/modules/recipe/data/model/recipe_placeholder_data.dart';

import 'package:casdon/modules/recipe/data/model/recipe_search_model.dart';

import 'package:casdon/auto_router.dart';
import 'package:casdon/modules/recipe/ui/widgets/play_orverlay_button.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:cached_network_image/cached_network_image.dart';

final searchKeywordProvider = StateProvider.autoDispose<String>((ref) => "");
final submittedKeywordProvider = StateProvider.autoDispose<String>((ref) => "");

@RoutePage()
class RecipeSearchScreen extends ConsumerStatefulWidget {
  const RecipeSearchScreen({super.key});
  @override
  ConsumerState<RecipeSearchScreen> createState() => _RecipeSearchScreenState();
}

class _RecipeSearchScreenState extends ConsumerState<RecipeSearchScreen> {
  late TextEditingController keywordController;
  late FocusNode focusNode;
  bool _isRefreshing = false;

  @override
  void initState() {
    super.initState();
    keywordController = TextEditingController();
    focusNode = FocusNode();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (mounted) {
        focusNode.requestFocus();
      }
    });
  }

  @override
  void dispose() {
    keywordController.dispose();
    focusNode.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final keyword = ref.watch(searchKeywordProvider);
    final submittedKeyword = ref.watch(submittedKeywordProvider);
    final asyncRecipes = ref.watch(recipeSearchProvider(submittedKeyword));
    final searchNotifier = ref.watch(
      recipeSearchProvider(submittedKeyword).notifier,
    );
    final tagsState = ref.watch(recipeSearchHistoryProvider);
    final tagsNotifier = ref.watch(recipeSearchHistoryProvider.notifier);

    if (keywordController.text != keyword) {
      keywordController.text = keyword;
      keywordController.selection = TextSelection.fromPosition(
        TextPosition(offset: keywordController.text.length),
      );
    }
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: _buildAppBar(context, ref, searchNotifier),
      body: NotificationListener<ScrollNotification>(
        onNotification: (notification) {
          // 在任何滚动事件中，首先检查刷新状态
          final isRefreshing = _isRefreshing || searchNotifier.isRefreshing;

          // 如果正在刷新，直接返回，不处理任何滚动事件
          if (isRefreshing) {
            return false;
          }

          // 如果是滚动结束事件且需要加载更多
          if (notification is ScrollEndNotification) {
            final metrics = notification.metrics;

            // 检查是否滚动到底部附近
            // 条件：
            // 1. pixels > 0：确保是向下滚动（下拉刷新时 pixels 可能是负数）
            // 2. pixels >= maxScrollExtent - 50：接近或到达底部
            // 3. extentBefore > 0：确保有内容在前面（防止下拉刷新时误判）
            // 4. extentAfter < 50：确实接近底部
            if (metrics.pixels > 0 &&
                metrics.extentBefore > 0 &&
                metrics.pixels >= metrics.maxScrollExtent - 50 &&
                metrics.extentAfter < 50) {
              // 最后一次检查刷新状态，确保在准备调用 loadMore 时没有开始刷新
              final finalIsRefreshing =
                  _isRefreshing || searchNotifier.isRefreshing;
              if (!finalIsRefreshing) {
                searchNotifier.loadMore();
              }
            }
          }
          return false;
        },
        child: RefreshIndicator(
          onRefresh: () async {
            // 在开始刷新前立即设置标志，防止并发操作
            if (_isRefreshing) {
              return;
            }
            // 立即设置刷新标志，防止滚动监听器触发 loadMore
            _isRefreshing = true;
            try {
              await searchNotifier.refresh();
            } finally {
              // 确保在 finally 中重置，即使出错也要重置
              _isRefreshing = false;
            }
          },
          child: CustomScrollView(
            slivers: [
              asyncRecipes.when(
                data: (recipes) {
                  if (keyword.isEmpty) {
                    return SliverToBoxAdapter(
                      child: _buildTagSelector(tagsState, tagsNotifier),
                    );
                  } else {
                    if (recipes.data.isNotEmpty) {
                      tagsNotifier.inserData(submittedKeyword);
                    } else {
                      return SliverToBoxAdapter(child: _buildNoDataWidget());
                    }

                    return SliverList(
                      delegate: SliverChildBuilderDelegate(
                        (context, index) =>
                            _buildRecipeItem(context, recipes.data[index]),
                        childCount: recipes.data.length,
                      ),
                    );
                  }
                },
                loading: () => const SliverToBoxAdapter(
                  child: Center(child: CircularProgressIndicator()),
                ),
                error: (err, _) => SliverFillRemaining(
                  hasScrollBody: false,
                  child: Column(
                    children: [
                      const Spacer(flex: 2),
                      _buildNoDataWidget(),
                      const Spacer(flex: 8),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  PreferredSizeWidget _buildAppBar(
    BuildContext context,
    WidgetRef ref,
    RecipeSearchNotifier notifier,
  ) {
    return AppBar(
      elevation: 0,
      backgroundColor: Colors.white,
      titleSpacing: 0,
      leading: IconButton(
        icon: const Icon(Icons.arrow_back_ios_new, color: Colors.black87),
        onPressed: () => Navigator.pop(context),
      ),
      title: Container(
        margin: EdgeInsets.only(right: 12.w),
        height: 36.h,
        decoration: BoxDecoration(
          color: const Color(0xFFF2F2F2),
          borderRadius: BorderRadius.circular(18),
        ),
        child: Row(
          children: [
            SizedBox(width: 10.w),
            const Icon(Icons.search, color: Colors.grey),
            SizedBox(width: 6.w),
            Expanded(
              child: TextField(
                controller: keywordController,
                focusNode: focusNode,
                autofocus: true,
                decoration: InputDecoration(
                  hintText: "搜索菜谱",
                  hintStyle: context.textTheme.bodyMedium!.copyWith(
                    color: context.customColorThemeNonNull.textColor2,
                  ),
                  border: InputBorder.none,
                  isDense: true,
                ),
                textInputAction: TextInputAction.search,
                onChanged: (value) {
                  ref.read(searchKeywordProvider.notifier).state = value;
                },
                onSubmitted: (value) {
                  ref.read(submittedKeywordProvider.notifier).state = value;
                },
              ),
            ),
            IconButton(
              icon: const Icon(Icons.close, size: 18, color: Colors.grey),
              onPressed: () async {
                keywordController.clear();
                ref.read(searchKeywordProvider.notifier).state = "";
                await notifier.clearData();
                focusNode.requestFocus();
              },
            ),
          ],
        ),
      ),
      bottom: PreferredSize(
        preferredSize: const Size.fromHeight(1),
        child: Container(
          width: double.infinity,
          color: context.customColorThemeNonNull.gray1,
          height: 1,
        ),
      ),
    );
  }

  Widget _buildRecipeItem(BuildContext context, RecipeSearchModel item) {
    return Material(
      color: Colors.white,
      child: InkWell(
        onTap: () {
          RecipeDetailRoute(
            recipeId: item.id,
            title: item.name,
            isSmart: item.isControl,
          ).push(context);
        },
        child: Container(
          color: Colors.white,
          padding: EdgeInsets.only(left: 12.w, right: 12.w, top: 12.h),
          child: Column(
            children: [
              Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  _buildImage(item),
                  SizedBox(width: 12.w),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          item.name,
                          style: context.textTheme.bodyMedium!.copyWith(
                            color: context.customColorThemeNonNull.textColor1,
                          ),
                        ),
                        SizedBox(height: 6.h),
                        Wrap(
                          spacing: 6.w,
                          runSpacing: 6.h,
                          children: [
                            if (item.isControl == true)
                              _buildTag("智能菜谱", context),
                            _buildTag(item.easyLevelDesc, context),
                            _buildTag(
                              "${item.cookTime}${item.cookTimeUnit ?? '分钟'}",
                              context,
                            ),
                          ],
                        ),
                        SizedBox(height: 6.h),
                        Text(
                          "${item.view ?? 0}人已查看",
                          style: context.textTheme.labelMedium!.copyWith(
                            color: context.customColorThemeNonNull.gy4,
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
              SizedBox(height: 12.h),
              Container(
                width: double.infinity,
                color: context.customColorThemeNonNull.gray1,
                height: 1,
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildImage(RecipeSearchModel model) {
    return SizedBox(
      width: 80.w,
      height: 80.w,
      child: ClipRRect(
        borderRadius: BorderRadius.circular(8.r),
        child: Stack(
          fit: StackFit.expand,
          children: [
            if (model.mainImg == null || model.mainImg!.isEmpty)
              Container(
                alignment: Alignment.center,
                color: const Color(0xFFF4F4F4),
                child: const Text(
                  "CASDON\n中国高端新厨电专家",
                  textAlign: TextAlign.center,
                  style: TextStyle(color: Colors.grey, fontSize: 10),
                ),
              )
            else
              CachedNetworkImage(
                imageUrl: model.mainImg!,
                fit: BoxFit.cover,
                errorWidget: (_, __, ___) =>
                    Image.network(recipePlaceHolderImgUrl, fit: BoxFit.cover),
              ),
            if (model.isvideo) const PlayOverlayButton(),
          ],
        ),
      ),
    );
  }

  Widget _buildTag(String text, BuildContext context) {
    Color bgColor;
    Color textColor;

    if (text == "智能菜谱") {
      bgColor = context.customColorThemeNonNull.brand1!;
      textColor = context.colorScheme.primary;
    } else {
      bgColor = context.customColorThemeNonNull.gray2!;
      textColor = context.customColorThemeNonNull.textColor3!;
    }

    return Container(
      padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 3.h),
      decoration: BoxDecoration(
        color: bgColor,
        borderRadius: BorderRadius.circular(6),
      ),
      child: Text(
        text,
        style: context.textTheme.labelSmall!.copyWith(color: textColor),
      ),
    );
  }

  Widget _buildNoDataWidget() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Image(
            image: Assets.images.noData.provider(),
            width: 80.w,
            height: 80.w,
          ),
          Text(
            "无搜索结果",
            style: context.textTheme.bodyMedium!.copyWith(
              color: context.customColorThemeNonNull.textColor2,
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildTagSelector(
    AsyncValue<List<String>> list,
    RecipeSearchHistoryNotifier notifier,
  ) {
    return list.when(
      data: (data) {
        if (data.isEmpty) {
          return Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                SizedBox(height: 128.h),
                Image(image: Assets.images.logoBg.provider()),
              ],
            ),
          );
        }
        return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                SizedBox(width: 16.w),
                Text(
                  "最近搜索",
                  style: context.textTheme.bodyLarge!.copyWith(
                    color: context.customColorThemeNonNull.textColor3,
                  ),
                ),
                const Spacer(),
                TextButton(
                  onPressed: () async {
                    await notifier.clear();
                  },
                  child: Text(
                    "  清空",
                    style: context.textTheme.bodyMedium!.copyWith(
                      color: context.colorScheme.primary,
                    ),
                  ),
                ),
                SizedBox(width: 16.w),
              ],
            ),
            ConstrainedBox(
              constraints: BoxConstraints(maxHeight: 5 * 42.h),
              child: CustomTagSelector<String>(
                options: data,
                value: [],
                multiChoice: false,
                wrapped: true,
                textStyle: context.textTheme.bodyMedium?.copyWith(
                  color: context.customColorThemeNonNull.textColor3,
                ),
                selectedTextStyle: context.textTheme.bodyMedium?.copyWith(
                  color: context.customColorThemeNonNull.textColor3,
                ),
                normalBgColor: context.customColorThemeNonNull.gray2,
                selectedBgColor: context.customColorThemeNonNull.gray2,
                onChanged: (value) {
                  Log.i("value = $value");
                  ref.read(searchKeywordProvider.notifier).state = value.first;
                },
              ),
            ),
          ],
        );
      },
      loading: () => const Center(child: SizedBox.shrink()),
      error: (err, _) => Center(child: SizedBox.shrink()),
    );
  }
}
